package com.kingviker.example.handler;

import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.util.concurrent.Future;
import io.netty.util.concurrent.GenericFutureListener;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.nio.charset.Charset;
import java.util.UUID;

public class MyClientHandler extends SimpleChannelInboundHandler<Long> {

    private Logger logger = LoggerFactory.getLogger(MyClientHandler.class);
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        logger.error("---------------------------------------------",cause);
        cause.printStackTrace();
        ctx.close();
    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        logger.info("---------->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>");
        ctx.writeAndFlush(10001);
        ChannelFuture channelFuture = ctx.writeAndFlush(10000);
        channelFuture.addListener(new GenericFutureListener<Future<? super Void>>() {
            @Override
            public void operationComplete(Future<? super Void> future) throws Exception {
                System.out.println(future.isDone());
                System.out.println(future.isCancellable());
                System.out.println(future.isSuccess());
                future.cause().printStackTrace();
            }
        });

//        ctx.writeAndFlush(10002L);
//        ctx.writeAndFlush(10003L);
//        ctx.writeAndFlush(Unpooled.copiedBuffer("helloworld", Charset.forName("utf-8")));
    }

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, Long msg) throws Exception {
        System.out.println(ctx.channel().remoteAddress()+","+msg);
//        ctx.channel().writeAndFlush("from server:"+ UUID.randomUUID().toString());
    }

}
